#include "GUI.h"
#include "WM.h"
#include "stdint.h"
#include <stdio.h>
#include "stm32f1xx_hal.h"

volatile uint32_t usCounter = 0;
uint32_t stepCounter = 0;

uint16_t stepVal[] = 
{
    1,
    10,
    100
};


static void cb_back(WM_MESSAGE *pMsg)
{
	WM_HWIN hWin = pMsg->hWin;
	
	switch(pMsg->MsgId)
	{
		case WM_PAINT:
		{
			GUI_SetBkColor(GUI_WHITE);
			GUI_Clear();
			
			break;
		}
		
		
	}
}

static void cb_win(WM_MESSAGE *pMsg)
{
    char valStr[20];
	WM_HWIN hWin = pMsg->hWin;
	
	switch(pMsg->MsgId)
	{
		case WM_PAINT:
		{
			//GUI_SetBkColor(GUI_BLACK);
			GUI_Clear();
			
            sprintf(valStr, "%04d us", usCounter);
            
			GUI_SetColor(GUI_WHITE);
			GUI_SetTextMode(GUI_TEXTMODE_TRANS);
			GUI_SetFont(GUI_FONT_32B_ASCII);
			GUI_DispStringHCenterAt(valStr, 64, 0);
            
            if(stepCounter % GUI_COUNTOF(stepVal) == 0)
            {
                GUI_DispStringAt("Off", 0, 32);
            }
            else
            {
                GUI_DispStringAt("On", 0, 32);
                
                if(stepCounter % GUI_COUNTOF(stepVal) == 0)
                {
                    GUI_DispStringAt("+-1", 80, 32);
                }
                else if(stepCounter % GUI_COUNTOF(stepVal) == 1)
                {
                    GUI_DispStringAt("+-10", 80, 32);
                }
                else if(stepCounter % GUI_COUNTOF(stepVal) == 2)
                {
                    GUI_DispStringAt("+-100", 80, 32);
                }
            }
			
			break;
		}
		
        case WM_TIMER:
        {
            int pwm;
            
            if(TIM2->CNT > 5000 && TIM2->CNT <= 65535)
            {
                TIM2->CNT = 1000;
            }
            
            usCounter = TIM2->CNT % 1000 + 1000;
            
            pwm = usCounter;
            TIM1->CCR1 = pwm;
            
            WM_InvalidateWindow(hWin);
            WM_RestartTimer(pMsg->Data.v, 100);
            break;
        
        }
        
        case WM_CREATE:
        {
            TIM2->CNT = 0;
            break;
        }
        
        default:
        {
            WM_DefaultProc(pMsg);
        }
		
	}
}

void GUI_Main(void)
{
    WM_HWIN hWin;
	GUI_Init();
	
	WM_SetCallback(WM_HBKWIN, cb_back);
	
	hWin = WM_CreateWindowAsChild(0,0,128,32, WM_HBKWIN, WM_CF_SHOW, cb_win, 0);

    WM_CreateTimer(hWin, 0, 100, 0);
    
	while(1)
	{
		GUI_Delay(10);
	}
	
}




